package uutalk.netcloud.talk.base.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.util.view.AlertDialogUtil;

/**
 * Created by Administrator on 2018/1/4.
 */

public class PermissionUtils {
    private static final String TAG = PermissionUtils.class.getSimpleName();
    public static final int CODE_RECORD_AUDIO = 0;
    public static final int CODE_GET_ACCOUNTS = 1;
    public static final int CODE_READ_PHONE_STATE = 2;
    public static final int CODE_CALL_PHONE = 3;
    public static final int CODE_CAMERA = 4;
    public static final int CODE_ACCESS_FINE_LOCATION = 5;
    public static final int CODE_ACCESS_COARSE_LOCATION = 6;
    public static final int CODE_READ_EXTERNAL_STORAGE = 7;
    public static final int CODE_WRITE_EXTERNAL_STORAGE = 8;
    public static final int CODE_MULTI_PERMISSION = 100;

    public static final String PERMISSION_RECORD_AUDIO = Manifest.permission.RECORD_AUDIO;
    public static final String PERMISSION_GET_ACCOUNTS = Manifest.permission.GET_ACCOUNTS;
    public static final String PERMISSION_READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE;
    public static final String PERMISSION_CALL_PHONE = Manifest.permission.CALL_PHONE;
    public static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    public static final String PERMISSION_ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    public static final String PERMISSION_ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    public static final String PERMISSION_READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;
    public static final String PERMISSION_WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;

    private static final String[] requestPermissions = {
            PERMISSION_RECORD_AUDIO,
            PERMISSION_GET_ACCOUNTS,
            PERMISSION_READ_PHONE_STATE,
            PERMISSION_CALL_PHONE,
            PERMISSION_CAMERA,
            PERMISSION_ACCESS_FINE_LOCATION,
            PERMISSION_ACCESS_COARSE_LOCATION,
            PERMISSION_READ_EXTERNAL_STORAGE,
            PERMISSION_WRITE_EXTERNAL_STORAGE
    };

    /**
     * 使用封装好的code申请权限
     *
     * @param activity
     * @param requestCode
     */
    public static void requestPermission(final Activity activity, final int requestCode) {
        if (activity == null) {
            return;
        }

        Log.i(TAG, "requestPermission requestCode:" + requestCode);
        if (requestCode < 0 || requestCode >= requestPermissions.length) {
            Log.e(TAG, "requestPermission illegal requestCode:" + requestCode);
            return;
        }

        final String requestPermission = requestPermissions[requestCode];

        //如果是6.0以下的手机，ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED，
        // 但是，如果用户关闭了你申请的权限，ActivityCompat.checkSelfPermission(),会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null)，
        // 你可以使用try{}catch(){},处理异常，也可以在这个地方，低于23就什么都不做，

//        int checkLocalPhonePermission;
//        try {
//            checkLocalPhonePermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
//        } catch (RuntimeException e) {
//            ActivityCompat.requestPermissions(activity,
//                    new String[]{requestPermission}, requestCode);
//            return;
//        }

        // 缺少权限时, 进入权限配置页面
        requestPermission(activity, requestCode, requestPermission);

    }

    /**
     * 请求单个权限
     * @param activity
     * @param requestCode
     * @param requestPermission
     */
    public static void requestPermission(final Activity activity, final int requestCode, String  requestPermission) {
        // 缺少权限时, 进入权限配置页面
        if (Build.VERSION.SDK_INT >= 23) {
            int checkLocalPhonePermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
            if (checkLocalPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity,
                        new String[]{requestPermission}, requestCode);
                return;
            }


            int myUid = 0;
            try {
                PackageManager pm = activity.getPackageManager();
                @SuppressLint("WrongConstant")
                ApplicationInfo ai = pm.getApplicationInfo(activity.getPackageName(), PackageManager.GET_ACTIVITIES);
                Log.d("!!", "!!" + ai.uid);
                myUid = ai.uid;
            } catch (Exception e) {
                e.printStackTrace();
            }

            if(RomUtils.checkIsMiuiRom()){
                //适配小米机型
                AppOpsManager appOpsManager = (AppOpsManager) activity.getSystemService(Context.APP_OPS_SERVICE);
                int checkOp = appOpsManager.checkOp(AppOpsManager.permissionToOp(requestPermission), myUid, activity.getPackageName());
                if (checkOp == AppOpsManager.MODE_IGNORED) {
                    Log.e(TAG, "没有被授权哦myUid"+myUid);
                    ActivityCompat.requestPermissions(activity,
                            new String[]{requestPermission}, requestCode);
                    return;
                }
            }
        }
    }

    /**
     * 显示单个权限请求结果
     * @param activity
     * @param permissions
     * @param msg
     */
    public static void requestSinglePermissionsResult(final Activity activity, String permissions, String msg){
        if(!ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions)){
            showOpenSettingActivity(activity, msg);
        }
    }

    /**
     * 提示窗口
     * @param activity
     * @param msg
     */
    private static void showOpenSettingActivity(final Activity activity, String msg){
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setMessage(msg)
                .setPositiveButton(LanguageUtil.getStringById(R.string.go_authorization), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        Intent intent = new Intent();
//                        //com.android.settings.ManageApplications
//                        intent.setAction(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
//                        Log.d(TAG, "getPackageName(): " + activity.getPackageName());
//                        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
//                        intent.setData(uri);
//                        activity.startActivity(intent);

//                        Intent localIntent = new Intent();
//                        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        if (Build.VERSION.SDK_INT >= 9) {
//                            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//                            localIntent.setData(Uri.fromParts("package", activity.getPackageName(), null));
//                        } else if (Build.VERSION.SDK_INT <= 8) {
//                            localIntent.setAction(Intent.ACTION_VIEW);
//                            localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
//                            localIntent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
//                        }
//                        activity.startActivity(localIntent);
                        dialog.dismiss();
                        JumpPermissionUtil.go2Setting(activity.getApplicationContext());

//                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                        // 根据包名打开对应的设置界面
//                        intent.setData(Uri.parse("package:" + activity.getPackageName()));
//                        activity.startActivity(intent);
                    }
                })
                .setNegativeButton(LanguageUtil.getStringById(R.string.cancle_authorization), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //finish();
                        dialog.dismiss();
                    }
                }).create();
        AlertDialogUtil.show(builder);
    }

    /**
     * 请求多个权限
     * @param activity
     * @param permissions
     * @param requestCode
     */
    public static boolean requestPermissions(final Activity activity, final String[] permissions, final int requestCode) {
        // 缺少权限时, 进入权限配置页面
        if (Build.VERSION.SDK_INT >= 23) {
            // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
            List<String> mPermissionList = new ArrayList<>();
            int length = permissions.length;
            for(int i=0; i<length; i++){
                if (ContextCompat.checkSelfPermission(activity, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }

            if(mPermissionList.size() > 0){
                String[] newPermissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
                ActivityCompat.requestPermissions(activity, newPermissions, requestCode);
                return false;
            }

        }
        return true;
    }
}
